// pages/vipCharge/vipCharge.js
const app = getApp()
const request = require("../../utils/request.js");
let config = require('../../config/config.js')
const log = require("../../utils/log.js");
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
var QQMapWx = require('../../utils/qqmap-wx-jssdk.js');
var qqmapsdk = new QQMapWx({
  key: config.map_key
})
let applyFlag = false
let diyMonthFlag = false
let monthFlag = false
let timeFlag = false
Page({
  data: {
    statusBarHeight: app.globalData.statusBarHeight,
    screenHeight: app.globalData.screenHeight,
    showSearchDialog: false,
    searcheRecord: '',
    searcheRecordDiy: [],
    showSubscribeModal: false,
    parkList: [],
    money: '',
    forbidShow: false, //禁停车是否显示
    inputLen: 8,
    isFocus: true,
    carNo: '',
    translateSpace: 0,
    inputType: 1, // 车牌输入类型，1简称，2数字或者字母,
    popShow: false,
    carNumList: [],
    isCard: true,
    cardIndex: 0,
    timeIndex: -1,
    checkParkList: [],
    allParkList: [],
    diyRuleId: '',
    isDiy: false,
    diyCardIndex: 0,
    tabbarIndex: 0,
    agreementShow: false,
    applicativeDialog: false,
    searchVal: '',
    nearbyParkList: [],
    nowParkList: [],
    monthPayRule: [],
    timerPayRule: [],
    applyPark: [],
    applyParkVal: '',
    applyParkNumber: 0,
    searchAddress: '',
    searchResult: [],
    searchResultDiy: [],
    searchPark: [],
    province: '',
    city: '',
    isPackaging: false,
    isNotSearchData: false,
    agreementVip: true,
    agreementDiy: true,
    agreementType: '',
    mobilePhone: '',
    couponDialog: false,
    isRec: false,
    searcheVip: {},
    diyCardList: [{
      name: '月卡',
      money: '',
      time: '30',
      select: true
    },
    {
      name: '季卡',
      money: '',
      time: '90',
      select: false
    },
    {
      name: '年卡',
      money: '',
      time: '365',
      select: false
    },
    ],
    couponID: 0,
    couponList: [],
    couponIndex: -1,
    checkedCouopn: {},
    skypeRuleList: [],
    skypeMoneyIndex: 0,
    skypeMoney: 0,
    totalPay: 0,
    btnLoading: false,
    bindRechargeMoney: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      couponID: options.couponID ? options.couponID : 0,
      tabbarIndex: options.index ? options.index : 0
    })
    let token = wx.getStorageSync('token');
    if (options.parkData) {
      this.setData({
        nowParkList: JSON.parse(options.parkData),
        isRec: true
      })
    }
    if (token) {
      this.getUserInfo()
      if (this.data.isRec) {
        // this.getTimerPayRule();
        this.getMonthPayRule();
        this.getSkypeRule()
        // this.getApplyPark()
      } else {
        this.getUserLocation()
      }
    } else {
      this.setData({
        verifyLoginDialog: true
      })
    }
    this.getCarNumList()
  },
  verifyLogin() {
    this.getUserInfo()
    if (this.data.isRec) {
      // this.getTimerPayRule();
      this.getMonthPayRule();
      // this.getApplyPark()
      this.getSkypeRule()
    } else {
      this.getUserLocation()
    }
  },
  /**
   * 获取用户信息
   */
  getUserInfo() {
    let that = this;
    let url = '/customer/info/getCustomerInfo'
    request.http(url, 'GET')
      .then((res) => {
        if (res.data.code == 200) {
          let user = res.data.data;
          if (user != null && user != undefined) {
            let phone = user.mobilePhone;
            that.setData({
              mobilePhone: phone
            })
          }
        } else {
          Toast.fail('获取数据失败');
        }
      })
  },
  /**
   * 获取手机号
   * @param {*} e 
   */
  getPhoneNumber: function (e) {
    var that = this;
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      let encryptedData = e.detail.encryptedData;
      let iv = e.detail.iv;
      wx.login({
        success(res) {
          let url = '/customer/info/bindMobilePhone'
          let params = {
            code: res.code,
            encryptedData: encryptedData,
            iv: iv
          }
          request.http(url, 'GET', params)
            .then(res => {
              if (res.data.code == 200) {
                let phone = res.data.data
                Toast.success('绑定成功');
                that.setData({
                  mobilePhone: phone
                })
                that.checkPop()
              }
            })
        }
      })
    }
  },
  /**
   * 获取充值金额
   */
  getSkypeRule() {
    let that = this
    request.http('/promotion/recharge-rule/getRechargeRule', 'get')
      .then(res => {
        console.log(res);
        let data = res.data
        if (data.code == 200) {
          that.setData({
            skypeRuleList: data.data,
            // totalPay: data.data[that.data.skypeMoneyIndex],
            skypeMoney: data.data[that.data.skypeMoneyIndex]
          })
          if (that.data.tabbarIndex == 0) {
            that.setData({
              totalPay: data.data[that.data.skypeMoneyIndex],
            })
          }
        }
      })
  },
  /**
   * 会员充值
   */
  selectSkype(e) {
    let index = e.currentTarget.dataset.index
    let money = e.currentTarget.dataset.money
    this.setData({
      skypeMoneyIndex: index,
      skypeMoney: money,
      totalPay: money
    })
  },
  /**
   * 自定义金额获取焦点
   */
  skypeInputFocus(e) {
    let money = e.detail.value
    this.setData({
      skypeMoneyIndex: -1,
      totalPay: money,
      skypeMoney: money
    })
  },
  /**
   * 获取自定义金额
   */
  getSkypeInput(e) {
    let money = e.detail.value
    console.log(money)
    if (money <= 0 || money > 9999) {
      wx.showToast({ title: '请输入0到9999内的数字', icon: 'none' })
      this.setData({
        skypeMoney: null,
        totalPay: null
      })
      return
    }
    this.setData({
      skypeMoney: money,
      totalPay: money
    })
  },
  /**
   * 时长支付规则
   */
  getTimerPayRule() {
    var that = this
    let url = '/promotion/duration-rule-paytype/getDurationRulePaytypeByParkId'
    let params = {
      parkId: that.data.nowParkList ? that.data.nowParkList.id : 0
    }
    request.http(url, 'GET', params)
      .then((res) => {
        var data = res.data
        if (data.code == '200') {
          var timerPayRule = data.data
          for (var i = 0; i < timerPayRule.length; i++) {
            timerPayRule[i]['checked'] = false
            timerPayRule[i]['average'] = (timerPayRule[i].amount / timerPayRule[i].duration).toFixed(2)
          }
          that.setData({
            timerPayRule
          })
        }
      })
      .catch(res => {
        that.setData({
          timerPayRule: []
        })
      })
  },
  /**
   * 获取月卡支付规则
   */
  getMonthPayRule(id) {
    var that = this
    let diyCardList = that.data.diyCardList
    let url = '/promotion/month-rule-paytype/getMonthRulePaytypeByParkId'
    let params = {
      parkId: id ? id : that.data.nowParkList ? that.data.nowParkList.id : 0
    }
    request.http(url, 'GET', params)
      .then((res) => {
        var data = res.data
        if (data.code == '200') {
          var monthPayRule = data.data
          monthPayRule.sort((a, b) => a.days - b.days); //按月季年排序
          if (data.data.length > 0) {
            for (var i = 0; i < monthPayRule.length; i++) {
              monthPayRule[i].beginTime = data.data[i].beginTime ? data.data[i].beginTime.substring(0, 5) : ''
              monthPayRule[i].endTime = data.data[i].beginTime ? data.data[i].endTime.substring(0, 5) : ''
              if (i == 0) {
                monthPayRule[i]['select'] = true
              } else {
                monthPayRule[i]['select'] = false
              }
            }
          }
          if (id) {
            for (var i = 0; i < data.data.length; i++) {
              let index = data.data[i].monthRentTypeId == '1' ? 0 : data.data[i].monthRentTypeId == '2' ? 1 : 2
              diyCardList[index].money = data.data[i] ? data.data[i].amount : ''
              diyCardList[index].sumAmount = data.data[i] ? data.data[i].sumAmount : ''
              diyCardList[index].customizeRuleId = data.data[i] ? data.data[i].monthRuleId : ''
              diyCardList[index].time = data.data[i] ? data.data[i].days : ''
              diyCardList[index].monthRuleId = data.data[i] ? data.data[i].monthRuleId : ''
            }
            for (var i = 0; i < diyCardList.length; i++) {
              if (diyCardList[i].sumAmount) {
                diyCardList[i].select = true
                break
              }
            }
            that.setData({
              diyCardList: diyCardList
            })
            if (that.data.tabbarIndex == 1) {
              that.setData({
                totalPay: diyCardList[0].sumAmount ? diyCardList[0].sumAmount : diyCardList[1].sumAmount ? diyCardList[1].sumAmount : diyCardList[2].sumAmount
              })
            }
          } else {
            that.setData({
              monthPayRule
            })
          }
        }
      })
      .catch(res => {
        that.setData({
          monthPayRule: []
        })
      })
  },
  /**
   * 选择时长
   * @param {*} event 
   */
  checkTime(event) {
    let index = event.currentTarget.dataset.index;
    let that = this;
    let timerPayRule = that.data.timerPayRule; //时长套餐列表
    let monthPayRule = that.data.monthPayRule; //通用会员卡列表
    for (let i = 0; i < monthPayRule.length; i++) {
      monthPayRule[i].select = false;
    }
    for (let i = 0; i < timerPayRule.length; i++) {
      if (i == index) {
        timerPayRule[i].checked = true
      } else {
        timerPayRule[i].checked = false
      }
    }
    that.setData({
      monthPayRule: monthPayRule,
      timerPayRule: timerPayRule,
      isCard: false,
      timeIndex: index,
      cardIndex: -1,
      isDiy: false
    })
  },
  /**
   * 选择月卡
   * @param {*} event 
   */
  cardCheck(event) {
    let that = this;
    let index = event.currentTarget.dataset.index;
    let timerPayRule = that.data.timerPayRule; //时长套餐列表
    let monthPayRule = that.data.monthPayRule; //通用会员卡列表

    for (let i = 0; i < timerPayRule.length; i++) {
      timerPayRule[i].checked = false;
    }
    for (let i = 0; i < monthPayRule.length; i++) {
      if (i == index) {
        monthPayRule[i].select = true
      } else {
        monthPayRule[i].select = false
      }
    }
    that.setData({
      timerPayRule: timerPayRule,
      monthPayRule: monthPayRule,
      isCard: true,
      cardIndex: index,
      timeIndex: -1,
      isDiy: false,
      totalPay: monthPayRule[index].sumAmount
    })
  },
  /**
   * 获取适用停车场搜索内容
   * @param {*} e 
   */
  getSearchVal(e) {
    this.setData({
      applyParkVal: e.detail.value
    })
  },
  /**
   * 搜索适用停车场
   */
  getApplyParkSearch() {
    // this.getApplyPark(this.data.applyParkVal, true)
  },
  /**
   * 获取适用停车场
   * @param {String} val 关键字 非必填 
   * @param {Boolean} isSearch 是否搜索
   */
  getApplyPark(val, isSearch) {
    var that = this
    let url = '/promotion/duration-rule-park/getDurationRuleParkByParkId'
    let params = {
      parkId: that.data.nowParkList ? that.data.nowParkList.id : 0
    };
    if (val) {
      params['keyword'] = val
    }
    request.http(url, 'GET', params)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          that.setData({
            applyPark: data.data
          })
          if (!isSearch) {
            that.setData({
              applyParkNumber: data.data.length
            })
          }
        }
        applyFlag = false
      })
      .catch(res => {
        applyFlag = false
      })
  },
  /**
   * 车牌号弹窗关闭
   */
  forbidShowClose() {
    this.setData({
      forbidShow: false,
      carNo: '',
      translateSpace: 0,
      showPlateInput: false
    })
  },
  /**
   * 输入弹窗打开
   */
  showforbidShow() {
    this.setData({
      forbidShow: true
    })
    this.onFocus();
  },
  /**
   * 设置车牌号输入框的值
   */
  setValue: function (e) {
    var that = this;
    that.setData({
      iptValue: e.detail.value
    });
  },
  /**
   * 自定义键盘点击
   */
  inputChange(e) {
    let that = this;
    let iptValue = that.data.iptValue;
    let value = e.detail;
    let keyBoardType = that.data.keyBoardType;
    that.setData({
      iptValue: iptValue + value
    })
    if (keyBoardType == 1) {
      that.setData({
        keyBoardType: 2
      })
    }
  },
  /**
   * 用于点击弹出键盘输入，space为键盘弹出后向上拉取的距离 
   */
  handleClick(e) {
    /* 150为键盘的高度 */
    let space = -(e.currentTarget.offsetTop - 150);
    /* regExp用于判断当前已输入的车牌号是否是中文，并让键盘显示中文还是英文输入 */
    let regExp = /^[\u4e00-\u9fa5]+/;
    let inputType = 1;
    if (regExp.test(this.data.carNo)) {
      inputType = 2;
    }
    this.setData({
      translateSpace: space,
      showPlateInput: true,
      inputType: inputType
    })
  },
  /**
   * 键盘输入操作
   */
  handlePlateChange(e) {
    let value = e.detail.value;
    let inputLen = this.data.inputLen;
    let type = e.detail.type;
    let carNo = this.data.carNo;
    if (carNo.length < inputLen) {
      carNo += value;
    }
    if (type == 1) {
      this.setData({
        inputType: 2
      })
    }
    this.setData({
      carNo

    })
  },
  /**
   * 点击键盘上的确定
   */
  handlePlateConfirm() {
    /* isCarPlate用于判断输入的车牌号是否符合规范 */
    if (!this.isCarPlate(this.data.carNo)) {
      wx.showToast({
        title: '请输入正确的车牌号',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    this.setData({
      translateSpace: 0,
      showPlateInput: false,
      inputType: 1
    })
  },
  /**
   * 用于键盘输入删除
   */
  handlePlateDelete(e) {
    let carNo = this.data.carNo;
    carNo = carNo.substring(0, carNo.length - 1);
    if (carNo.length == 0) {
      this.setData({
        inputType: 1
      })
    }
    this.setData({
      carNo,
    })
  },
  /**
   * 判断车牌号
   * @param {String} value 车牌号
   */
  isCarPlate(value) {
    return /^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/.test(value);
  },
  /**
   * 输入车牌号
   */
  onFocus: function (e) {
    var that = this;
    let regExp = /^[\u4e00-\u9fa5]+/;
    let inputType = 1;
    if (regExp.test(that.data.carNo)) {
      inputType = 2;
    }
    that.setData({
      showPlateInput: true,
      inputType: inputType
    });
  },
  selectSearchPark(e) {
    let index = e.currentTarget.dataset.index
    let type = e.currentTarget.dataset.type
    let mold = e.currentTarget.dataset.mold
    if (type == 'history') {
      this.getNearbyPark(e.currentTarget.dataset.lng, e.currentTarget.dataset.lat)
    } else {
      let searchResultDiy
      let record = {}
      if (mold == 'park') {
        searchResultDiy = this.data.searchPark
        record = {
          place: searchResultDiy[index].parkName,
          latitude: searchResultDiy[index].latitude,
          longitude: searchResultDiy[index].longitude,
          address: searchResultDiy[index].parkAddress
        }
      } else if (mold == 'address') {
        searchResultDiy = this.data.searchResultDiy
        record = {
          place: searchResultDiy[index].title,
          latitude: searchResultDiy[index].location.lat,
          longitude: searchResultDiy[index].location.lng,
          address: searchResultDiy[index].address
        }
      }
      var searcheVip = wx.getStorageSync('searcheVip');
      if (Array.isArray(searcheVip)) {
        if (searcheVip.length == 2) {
          searcheVip.splice(1, 1);
          searcheVip.unshift(record);
        } else {
          searcheVip.unshift(record);
        }
      } else {
        searcheVip = [];
        searcheVip.push(record);
      }
      wx.setStorageSync('searcheVip', searcheVip);
      this.getNearbyPark(record.longitude, record.latitude)
    }
    this.setData({
      searchResultDiy: []
    })
  },
  /**
   * 获取附近停车点
   * @param {Number} longitude 经度
   * @param {Number} latitude 纬度
   */
  getNearbyPark(longitude, latitude) {
    let that = this
    let record = {
      longitude: longitude,
      latitude: latitude,
      // type: 0,
      currentPage: 1,
      pageSize: 10
    }
    let url = "/park/info/get-nearby-park-has-month-rule-list";
    if (this.data.tabbarIndex == 1) {
      url = "/park/info/getNearbyParkList";
    }
    request.http(url, 'GET', record)
      .then((res) => {
        if (res.data.code == 200) {
          let parkList = res.data.data.records;
          if (parkList.length <= 0) {
            wx.showToast({
              title: '当前地点附近暂无停车场可用',
              icon: 'none'
            })
          }
          that.setData({
            searchResult: parkList
          })
        }
      })
  },
  /**
   * diy选择车场
   */
  selectPark(e) {
    let index = e.currentTarget.dataset.index
    let type = e.currentTarget.dataset.type
    let checkParkList = this.data.checkParkList
    let searcheRecordDiy = this.data.searchResult
    let tabbarIndex = this.data.tabbarIndex

    if (tabbarIndex == 2) {
      let selctPark
      if (type == 'history') {
        selctPark = this.data.searcheRecordDiy[index]
      } else if (type == 'nearby') {
        selctPark = this.data.nearbyParkList[index]
      } else {
        selctPark = this.data.searchResult[index]
      }
      if (selctPark.hasMonthRule == 0) {
        Toast('当前停车场暂未开通服务')
        return
      }
      for (var i = 0; i < checkParkList.length; i++) {
        if (selctPark.id == checkParkList[i].id) {
          wx.showToast({
            title: '请不要选择重复停车场',
            icon: 'none'
          })
          return
        }
      }
      checkParkList = checkParkList.concat(selctPark)
      if (checkParkList.length > 5) {
        Toast('最多选择五个停车场')
        return
      }
      let diyCardList = this.data.diyCardList
      for (let i = 0; i < diyCardList.length; i++) {
        diyCardList[i].select = false
      }
      this.setData({
        checkParkList: checkParkList,
        diyCardIndex: 0
      })
      if (checkParkList.length > 1) {
        this.calculateDiyPrice()
      } else {
        this.getMonthPayRule(checkParkList[0].id)
      }
    } else {
      let selctPark
      if (type == 'history') {
        selctPark = this.data.searcheRecordDiy[index]
      } else if (type == 'nearby') {
        selctPark = this.data.nearbyParkList[index]
      } else {
        selctPark = this.data.searchResult[index]
      }
      if (selctPark.hasMonthRule == 0) {
        Toast('当前停车场暂未开通服务')
        return
      }
      this.setData({
        nowParkList: selctPark
      })
      // this.getTimerPayRule();
      this.getMonthPayRule();
      // this.getApplyPark(this.data.searchAddress)
      let from = {
        latitude: this.data.latitude,
        longitude: this.data.longitude
      }
      let to = [{
        latitude: selctPark.latitude,
        longitude: selctPark.longitude
      }]
      var that = this
      this.calculateDistance(from, to, function (res) {
        let data = res
        if (data.status == 0) {
          let distance = data.result.elements[0].distance
          let nowParkList = that.data.nowParkList
          nowParkList.distances = (distance / 1000).toFixed(2)
          that.setData({
            nowParkList: nowParkList
          })
        }
      })
    }
    this.hiddenSearchDialog()
  },
  /**
   * 计算定制价格
   */
  calculateDiyPrice() {
    let that = this
    let checkParkList = that.data.checkParkList
    let parkIdArr = []
    let diyCardList = that.data.diyCardList
    for (var i = 0; i < checkParkList.length; i++) {
      parkIdArr.push(checkParkList[i].id)
    }
    let url = '/promotion/customize-rule/computePrice'
    let params = {
      parkIds: parkIdArr
    }
    request.http(url, 'POST', params)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          diyCardList[0].money = data.data.monthTotalAmount
          diyCardList[0].sumAmount = data.data.monthTotalAmount
          diyCardList[0].customizeRuleId = data.data.customizeRuleId
          diyCardList[0].time = data.data.monthDays
          diyCardList[1].money = data.data.quarterTotalAmount
          diyCardList[1].sumAmount = data.data.quarterTotalAmount
          diyCardList[1].customizeRuleId = data.data.customizeRuleId
          diyCardList[1].time = data.data.quarterDays
          diyCardList[2].money = data.data.yearTotalAmount
          diyCardList[2].sumAmount = data.data.yearTotalAmount
          diyCardList[2].customizeRuleId = data.data.customizeRuleId
          diyCardList[2].time = data.data.yearDays
          for (var i = 0; i < diyCardList.length; i++) {
            if (diyCardList[i].sumAmount) {
              diyCardList[i].select = true
              break
            }
          }
          that.setData({
            diyCardList: diyCardList,
            totalPay: diyCardList[0].sumAmount ? diyCardList[0].sumAmount : diyCardList[1].sumAmount ? diyCardList[1].sumAmount : diyCardList[2].sumAmount
          })
        }
      })
  },
  /**
   * 开通定制月卡
   */
  openDiyCard() {
    if (diyMonthFlag) {
      return
    }
    diyMonthFlag = true
    let that = this;
    let checkParkList = that.data.checkParkList;
    let parkIds = []
    for (let i = 0; i < checkParkList.length; i++) {
      parkIds.push(checkParkList[i].id);
    }
    let index = that.data.diyCardIndex;
    let coupon = that.data.checkedCouopn
    let carCardNum = that.data.carNo;
    let cardList = that.data.diyCardList;
    let totalFee = cardList[index].money;
    if (totalFee == '') {
      wx.showToast({
        title: '选中无规则车场，请重新选择',
        icon: 'none'
      })
      return
    }
    let url = "/customer/card/buyCustomizeCard"
    var params = {
      carId: carCardNum,
      parkIdList: parkIds,
      paidAmount: totalFee,
      monthRentTypeId: index == 0 ? '1' : index == 1 ? '2' : '3',
    };
    if (checkParkList.length <= 1) {
      // Toast('至少选择两个停车场！')
      params['monthRuleId'] = cardList[index].monthRuleId
      that.openCard(params)
      return
    }
    if (coupon.ticketId) {
      that.countCoupon({
        paidAmount: totalFee,
        receivableAmount: totalFee,
        ticketId: coupon.ticketId,
        custTicketId: coupon.id,
        rentType: 2
      },
        function (res) {
          params.paidAmount = res.data.paidAmount
          params['ticketId'] = coupon.ticketId
          params['custTicketId'] = coupon.custTicketId
          toPay()
        }
      )
    } else {
      toPay()
    }

    function toPay() {
      request.http(url, 'POST', params)
        .then((res) => {
          log.info('接口' + url + ':' + JSON.stringify(res.data))
          if (res.data.code == 200) {
            let orderCode = res.data.data.orderCode
            that.forbidShowClose();
            let body = res.data.data;
            //支付
            wx.requestPayment({
              timeStamp: res.data.data.timeStamp, // 时间戳，必填（后台传回）
              nonceStr: res.data.data.nonceStr, // 随机字符串，必填（后台传回）
              package: res.data.data.package, // 统一下单接口返回的 prepay_id 参数值，必填（后台传回）
              signType: 'MD5', // 签名算法，非必填，（预先约定或者后台传回）
              paySign: res.data.data.paySign, // 签名 ，必填 （后台传回）
              success: function (res) { // 成功后的回调函数
                that.getPayState('CUSTOMIZE', orderCode)
              },
              fail(res) {
                // Toast.fail('支付失败');
                console.log(res)
              }
            })
          } else {
            Toast.fail('开通失败');
          }
          diyMonthFlag = false
        }).catch((errMsg) => {
          diyMonthFlag = false
        });
    }
  },
  /**
   * 开通月卡
   */
  openCard(data) {
    if (monthFlag) {
      return
    }
    monthFlag = true
    let that = this;
    let monthPayRule = that.data.monthPayRule;
    if (monthPayRule.length <= 0) {
      wx.showToast({
        title: '请您先选择收费规则',
        icon: 'none'
      })
      return
    }
    let index = that.data.cardIndex;
    let carCardNum = that.data.carNo;
    let coupon = that.data.checkedCouopn
    let paytype = monthPayRule[index].monthRentTypeId;
    let ruleId = monthPayRule[index].monthRuleId;
    let totalFee = monthPayRule[index].amount;
    let parkId = that.data.nowParkList.id;
    let url = "/customer/card/buyMonthCard";
    let params = {
      carId: carCardNum,
      monthRentTypeId: paytype,
      monthRuleId: ruleId,
      paidAmount: totalFee,
      parkId: parkId
    }
    if (data) {
      params = {
        carId: data.carId,
        monthRentTypeId: data.monthRentTypeId,
        monthRuleId: data.monthRuleId,
        paidAmount: data.paidAmount,
        parkId: data.parkIdList[0]
      }
    }
    if (coupon.ticketId) {
      that.countCoupon({
        paidAmount: totalFee,
        receivableAmount: totalFee,
        ticketId: coupon.ticketId,
        custTicketId: coupon.id,
        rentType: 0
      },
        function (res) {
          params.paidAmount = res.data.paidAmount
          params['ticketId'] = coupon.ticketId
          params['custTicketId'] = coupon.custTicketId
          toPay()
        }
      )
    } else {
      toPay()
    }

    function toPay() {
      request.http(url, 'POST', params)
        .then((res) => {
          log.info('接口' + url + ':' + JSON.stringify(res.data))
          if (res.data.code == 200) {
            let orderCode = res.data.data.orderCode
            that.forbidShowClose();
            //支付
            wx.requestPayment({
              timeStamp: res.data.data.timeStamp, // 时间戳，必填（后台传回）
              nonceStr: res.data.data.nonceStr, // 随机字符串，必填（后台传回）
              package: res.data.data.package, // 统一下单接口返回的 prepay_id 参数值，必填（后台传回）
              signType: 'MD5', // 签名算法，非必填，（预先约定或者后台传回）
              paySign: res.data.data.paySign, // 签名 ，必填 （后台传回）
              success: function (res) { // 成功后的回调函数
                that.getPayState('MONTH', orderCode)
              },
              fail(res) {
                // Toast.fail('支付失败');
                console.log(res)
              }
            })
          } else {
            Toast.fail('开通失败');
          }
          monthFlag = false
          diyMonthFlag = false
        })
        .catch((errMsg) => {
          monthFlag = false
          diyMonthFlag = false
        });
    }
  },
  /**
   * 查询车牌列表
   */
  getCarNumList(carName) {
    let that = this;
    let url = "/customer/car/getCustomerCarList";
    request.http(url, 'GET')
      .then((res) => {
        if (res.data.code == 200) {
          let list = res.data.data;
          let carNo = 0
          if (list != null && list.length > 0) {
            for (let i = 0; i < list.length; i++) {
              if (i == 0) {
                list[i].select = true
              } else {
                list[i].select = false
              }
              if (carName == list[i].carNumber) {
                carNo = list[i].id
              }
            }
            if (carName) {
              that.setData({
                carNumList: list,
                carNo: carNo
              })
              if (this.data.tabbarIndex == 2) {
                that.openDiyCard();
              } else {
                if (that.data.isCard) {
                  that.openCard();
                } else {
                  that.forbidShowClose();
                  that.timeMiniPay();
                }
              }
              return
            }
            that.setData({
              carNumList: list
            })
          } else {
            that.setData({
              carNumList: []
            })
          }
        }
      })
  },
  /**
   * 提交按钮
   */
  getCarNumberList() {
    let that = this;
    let carNo = ''
    let carNumList = that.data.carNumList;
    for (let i = 0; i < carNumList.length; i++) {
      if (carNumList[i].select) {
        carNo = carNumList[i].id
      }
    }
    that.setData({
      carNo: carNo
    })
    this.popShowClose();
    let tabbarIndex = this.data.tabbarIndex
    if (tabbarIndex == 2) {
      this.openDiyCard();
    } else {
      this.openCard();
    }
  },
  /**
   * 绑定车牌号
   */
  bindCarNumber() {
    let that = this;
    let carNo = that.data.carNo;
    let isDiy = that.data.isDiy;
    if (!that.isCarPlate(that.data.carNo)) {
      Toast('请输入正确车牌号');
      return;
    }
    let url = '/customer/car/addCustomerCar'
    let params = {
      carNumber: carNo
    }
    request.http(url, 'POST', params)
      .then((res) => {
        if (res.data.code == 200) {
          Toast.success('绑定成功');
          that.setData({
            forbidShow:false,
            inputLen:[],
            showPlateInput: false,
          });
          that.getCarNumList(carNo)
        } else {
          Toast.fail(res.data.message);
        }
      })
  },
  /**
   * 弹窗展示
   */
  showPop() {
    this.setData({
      popShow: true
    })
  },
  /**
   * 关闭弹窗展示
   */
  popShowClose() {
    this.setData({
      popShow: false
    })
  },
  /**
   * 选择不同的弹窗弹起
   */
  checkPop() {
    let that = this;
    let carNumList = that.data.carNumList;
    let tabbarIndex = that.data.tabbarIndex
    if (tabbarIndex == 1) {
      if (!that.data.agreementVip) {
        Toast('请同意会员协议')
        return
      }
      if (that.data.monthPayRule.length <= 0 && that.data.timerPayRule.length <= 0) {
        Toast('车场暂未vip服务')
        return
      }
    } else {
      if (!that.data.agreementDiy) {
        Toast('请同意会员协议')
        return
      }
    }
    //暂时应该没用  先注释掉
    // if (carNumList != null && carNumList.length > 0) {
    //   if (that.data.isCard || that.data.tabbarIndex == 2) {
    //     that.showPop();
    //   } else {
    //     that.timeMiniPay()
    //   }
    // } else {
    //   // that.showforbidShow();
    // }
  },
  /**
   * 开通时长
   */
  timeMiniPay() {
    if (timeFlag) {
      return
    }
    timeFlag = true
    let that = this;
    let timerPayRule = that.data.timerPayRule;
    let checkIndex = that.data.timeIndex;
    let coupon = that.data.checkedCouopn
    let durationRuleFeeScaleId = timerPayRule[checkIndex].id;
    let ruleId = timerPayRule[checkIndex].durationRuleId;
    let totalFee = timerPayRule[checkIndex].amount;
    let url = '/customer/card/buyDurationCard'
    let params = {
      durationRuleFeeScaleId: durationRuleFeeScaleId,
      durationRuleId: ruleId,
      paidAmount: totalFee
    }
    if (coupon.ticketId) {
      that.countCoupon({
        paidAmount: totalFee,
        receivableAmount: totalFee,
        ticketId: coupon.ticketId,
        custTicketId: coupon.id,
        rentType: 1
      },
        function (res) {
          params.paidAmount = res.data.paidAmount
          params['ticketId'] = coupon.ticketId
          params['custTicketId'] = coupon.custTicketId
          toPay()
        }
      )
    } else {
      toPay()
    }

    function toPay() {
      request.http(url, 'POST', params)
        .then((res) => {
          log.info('接口' + url + ':' + JSON.stringify(res.data))
          let orderCode = res.data.data.orderCode
          if (res.data.code == 200) {
            if (res.data.data != null) {
              wx.requestPayment({
                timeStamp: res.data.data.timeStamp,
                nonceStr: res.data.data.nonceStr,
                package: res.data.data.package,
                signType: 'MD5',
                paySign: res.data.data.paySign,
                success(res) {
                  that.getPayState('DURATION', orderCode)
                },
                fail(res) {
                  // Toast.fail('支付失败');
                  console.log(res)
                }
              })
            }
          }
          timeFlag = false
        }).catch((errMsg) => {
          timeFlag = false
        });

    }
  },
  /**
   * 选择车牌号
   */
  carNumCheck(event) {
    let that = this;
    let index = event.currentTarget.dataset.index;
    let carNumList = that.data.carNumList;
    for (let i = 0; i < carNumList.length; i++) {
      if (i == index) {
        carNumList[i].select = true
      } else {
        carNumList[i].select = false
      }
    }
    that.setData({
      carNo: carNumList[index].carCardNum,
      carNumList: carNumList
    })
  },
  /**
   * 通用会员卡展示弹窗
   */
  showParkModal() {
    this.setData({
      showSubscribeModal: true
    })
  },
  /**
   * 关闭通用会员卡展示弹窗
   */
  closeParksModal() {
    this.setData({
      showSubscribeModal: false
    })
  },
  /**
   * 自定义会员卡选择停车场
   */
  checkPark(event) {
    let that = this;
    let index = event.currentTarget.dataset.index;
    let parkList = that.data.allParkList;
    let checkNum = 0;
    if (!parkList[index].select) {
      for (let i = 0; i < parkList.length; i++) {
        if (parkList[i].select) {
          checkNum += 1;
        }
      }
      if (checkNum == 5) {
        Toast('最多可以选5家停车场');
        return
      } else {
        parkList[index].select = !parkList[index].select;
      }
    } else {
      parkList[index].select = !parkList[index].select
    }
    that.setData({
      allParkList: parkList,
    })
  },
  /**
   * 展示选择停车场弹窗
   */
  showDiyParkModal() {
    this.setData({
      showSearchDialog: true,
      isPackaging: true
    })
  },
  /**
   * 删除已经选择的停车场
   */
  deleCheckPark(event) {
    let index = event.currentTarget.dataset.index;
    let that = this;
    let allParkList = that.data.allParkList;
    let diyCardList = that.data.diyCardList;
    let checkParkList = that.data.checkParkList;
    for (let i = 0; i < allParkList.length; i++) {
      if (allParkList[i].id == checkParkList[index].id) {
        allParkList[i].select = false
      }
    }
    for (let i = 0; i < diyCardList.length; i++) {
      diyCardList[i].select = false
    }
    checkParkList.splice(index, 1);
    that.setData({
      checkParkList: checkParkList,
      allParkList: allParkList,
      diyCardIndex: 0

    })
    if (checkParkList.length == 1) {
      that.getMonthPayRule(checkParkList[0].id)
    } else if (checkParkList.length > 1) {
      that.calculateDiyPrice();
    }
    if (checkParkList.length <= 0) {
      that.setData({
        diyCardList: [{
          name: '月卡',
          money: '',
          time: '30',
          select: true
        },
        {
          name: '季卡',
          money: '',
          time: '90',
          select: false
        },
        {
          name: '年卡',
          money: '',
          time: '365',
          select: false
        }],
        totalPay: 0
      })
    }
  },
  /**
   * 选择定制月卡
   */
  checkDiyCard(event) {
    let that = this;
    let index = event.currentTarget.dataset.index;
    let timeList = that.data.timeList; //时长套餐列表
    let cardList = that.data.cardList; //通用会员卡列表
    let diyCardList = that.data.diyCardList;
    for (let i = 0; i < diyCardList.length; i++) {
      if (i == index) {
        diyCardList[i].select = true
      } else {
        diyCardList[i].select = false
      }
    }
    that.setData({
      timeList: timeList,
      cardList: cardList,
      isCard: true,
      diyCardIndex: index,
      diyCardList: diyCardList,
      isDiy: true,
      totalPay: diyCardList[index].sumAmount
    })
  },
  /**
   * 切换tab栏
   */
  selectTabbar(e) {
    let index = e.currentTarget.dataset.index
    if (this.data.tabbarIndex == index) {
      return
    }
    this.setData({
      tabbarIndex: index
    })
  },
  /**
   * swiper current 切换
   */
  changeCurrent(e) {
    let index = e.detail.current
    let totalPay = 0
    if (index == 0) {
      totalPay = this.data.skypeRuleList[this.data.skypeMoneyIndex]
    } else if (index == 1) {
      totalPay = this.data.monthPayRule[this.data.cardIndex] ? this.data.monthPayRule[this.data.cardIndex].sumAmount : 0
    } else if (index == 2) {
      totalPay = this.data.diyCardList[this.data.diyCardIndex].sumAmount ? this.data.diyCardList[this.data.diyCardIndex].sumAmount : this.data.diyCardList[this.data.diyCardIndex + 1].sumAmount ? this.data.diyCardList[this.data.diyCardIndex + 1].sumAmount : 0
    }
    this.setData({
      tabbarIndex: index,
      searchResult: [],
      totalPay: totalPay
    })
  },
  /**
   * 用户协议弹窗
   */
  showAgreement(e) {
    let type = e.currentTarget.dataset.type
    this.setData({
      agreementShow: true,
      agreementType: type
    })
  },
  /**
   * 关闭用户协议弹窗
   */
  showAgreementClose() {
    this.setData({
      agreementShow: false
    })
  },
  /**
   * 同意协议按钮事件
   */
  showAgreementCloseEvent(e, a) {
    let agreement = e.detail
    this.setData({
      agreementVip: agreement
    })
  },
  /**
   * 底部弹窗弹出
   */
  showBottomPop() {
    if (this.data.checkParkList.length >= 5) {
      Toast('最多选择五个停车场')
      return
    }
    let searcheRecordDiy = wx.getStorageSync('searcheRecordDiy');
    if (searcheRecordDiy != null) {
      this.setData({
        searcheRecordDiy: searcheRecordDiy
      })
    }
    let searcheVip = wx.getStorageSync('searcheVip');
    if (searcheVip != null) {
      this.setData({
        searcheVip: searcheVip
      })
    }
    this.setData({
      showSearchDialog: true
    })
  },
  /**
   * 底部弹窗关闭
   */
  hiddenSearchDialog() {
    this.setData({
      showSearchDialog: false,
      isPackaging: false,
      isNotSearchData: false,
      searchAddress: '',
      searchResultDiy: [],
    })
  },
  /**
   * 打开适用车场弹窗
   */
  showApplicativeDialog() {
    if (applyFlag) {
      return
    }
    applyFlag = true
    this.setData({
      applicativeDialog: true
    })
    // this.getApplyPark()
  },
  /**
   * 关闭适用车场弹窗
   */
  hiddenApplicativeDialog() {
    this.setData({
      applicativeDialog: false,
      searchVal: '',
      applyPark: []
    })
  },
  /**
   * 获取搜索输入框的文字
   */
  getSearch(event) {
    let that = this
    this.setData({
      searchAddress: event.detail.value
    })
    // this.searchStopPark(event.detail.value)
    qqmapsdk.getSuggestion({
      keyword: event.detail.value,
      region: this.data.city,
      page_size: 10,
      success(res) {
        var data = res.data
        that.setData({
          searchResultDiy: data,
          searchResult: [],
          isNotSearchData: false
        })
        if (data.length <= 0) {
          that.setData({
            isNotSearchData: true
          })
        }
      }
    })
  },
  searchStopPark(val) {
    let that = this
    if (!val) {
      that.setData({
        searchPark: []
      })
      return
    }
    let url = '/park/info/getParkByName'
    let params = {
      keyword: val
    }
    request.http(url, 'GET', params)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          that.setData({
            searchPark: data.data
          })
        }
      })
  },
  /**
   * 点击搜索按钮
   */
  searchClick() {
    let that = this;
    let searchAddress = that.data.searchAddress;
    if (searchAddress == 'undefined' || searchAddress == 'null') {
      Toast('请输入目的地');
      return
    }

    return
    let url = '/promotion/month-rule-park/getMonthRuleParkList'
    let params = {
      keyword: searchAddress
    }
    request.http(url, 'GET', params)
      .then(res => {
        var data = res.data
        if (data.code == 200) {
          that.setData({
            searchAddress: ''
          })
          if (data.data.length <= 0) {
            that.setData({
              isNotSearchData: true,
              searchResultDiy: data.data
            })
            return
          }
          var searcheRecordDiy = wx.getStorageSync('searcheRecordDiy');
          if (Array.isArray(searcheRecordDiy)) {
            if (searcheRecordDiy.length == 2) {
              searcheRecordDiy.splice(1, 1);
              searcheRecordDiy.unshift(data.data[0]);
            } else {
              searcheRecordDiy.unshift(data.data[0]);
            }
          } else {
            searcheRecordDiy = [];
            searcheRecordDiy.push(data.data[0]);
          }
          wx.setStorageSync('searcheRecordDiy', searcheRecordDiy);
          that.setData({
            searchResultDiy: data.data,
            isNotSearchData: false
          })
        }
      })
      .catch(res => {

      })
  },
  /**
   * 获取用户当前位置
   */
  getUserLocation() {
    let that = this;
    wx.getLocation({
      type: 'gcj02',
      success(res) {
        let longitude = res.longitude;
        let latitude = res.latitude;
        that.setData({
          longitude: res.longitude,
          latitude: res.latitude,
        });
        //获取全部停车场
        that.getParks(longitude, latitude);
        that.getLocal(latitude, longitude);
      }
    })
  },
  /**
   * 获取当前地理位置
   * @param {Number} latitude 纬度
   * @param {Number} longitude 经度
   */
  getLocal: function (latitude, longitude) {
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        let province = res.result.ad_info.province
        let city = res.result.ad_info.city
        vm.setData({
          province: province,
          city: city
        })
      },
      fail: function (res) {
        Toast.fail('获取位置失败，请重新登录');
      }
    });
  },
  /**
   * 计算两点之间距离
   * @param {Object} from 起始点经纬度
   * @param {Array} to 结束点经纬度
   * @param {Function} callback 回调函数
   */
  calculateDistance(from, to, callback) {
    qqmapsdk.calculateDistance({
      mode: 'driving',
      from,
      to,
      success(res) {
        callback(res)
      },
      fail: function (error) {
        console.error(error);
      },
    })
  },
  /**
   * 获取附近停车场
   * @param {*} longitude 经度
   * @param {*} latitude 纬度
   */
  getParks(longitude, latitude) {
    let that = this;
    let record = {
      longitude: longitude,
      latitude: latitude,
      currentPage: 1,
      pageSize: 5
    }
    let url = "/park/info/getNearbyParkList";
    request.http(url, 'GET', record)
      .then((res) => {
        if (res.data.code == 200) {
          let parkList = res.data.data.records;
          that.calculateDistance({
            longitude: longitude,
            latitude: latitude
          },
            [{
              longitude: parkList[0].longitude,
              latitude: parkList[0].latitude
            }],
            function (res) {
              parkList[0].distances = (res.result.elements[0].distance / 1000).toFixed(2)
              that.setData({
                nearbyParkList: parkList,
                nowParkList: parkList[0]
              })
              // that.getTimerPayRule();
              that.getMonthPayRule();
              that.getSkypeRule()
              // that.getApplyPark()
            }
          )
        }
      })
  },
  showMapMark(e) {
    let that = this
    let nearbyParkLists = this.data.nearbyParkList
    let index = e.currentTarget.dataset.index
    let nearbyParkList = nearbyParkLists[index]
    console.log(nearbyParkList);
    if (this.data.tabbarIndex == 1) {
      let from = {
        latitude: this.data.latitude,
        longitude: this.data.longitude
      }
      let to = [{
        latitude: nearbyParkList.latitude,
        longitude: nearbyParkList.longitude
      }]
      this.calculateDistance(from, to, function (res) {
        let data = res
        if (data.status == 0) {
          let distance = data.result.elements[0].distance
          nearbyParkList['distances'] = (distance / 1000).toFixed(2)
          that.setData({
            nowParkList: nearbyParkList,
            showSearchDialog: false,
            isRec: true
          })
          // that.getTimerPayRule();
          that.getMonthPayRule();
          // that.getApplyPark()
        }
      })
    } else {
      let selctPark = nearbyParkList
      let checkParkList = this.data.checkParkList
      for (var i = 0; i < checkParkList.length; i++) {
        if (selctPark.id == checkParkList[i].id) {
          wx.showToast({
            title: '请不要选择重复停车场',
            icon: 'none'
          })
          return
        }
      }
      checkParkList = checkParkList.concat(selctPark)
      if (checkParkList.length > 5) {
        Toast('最多选择五个停车场')
        return
      }
      this.setData({
        checkParkList: checkParkList
      })
      if (checkParkList.length > 1) {
        this.calculateDiyPrice()
      } else {
        this.getMonthPayRule(checkParkList[0].id)
      }
      this.hiddenSearchDialog()
    }
  },
  /**
   * 在地图中打开推荐位置
   */
  toMapNavigation() {
    let parkData = this.data.nowParkList
    let latitude = Number(parkData.latitude)
    let longitude = Number(parkData.longitude)
    wx.openLocation({
      latitude,
      longitude,
      name: parkData.parkName,
      address: parkData.parkAddress,
      scale: 14
    })
  },
  /**
   * 在地图中打开历史搜索位置
   */
  historyToMap(e) {
    let index = e.currentTarget.dataset.index;
    let parkData = this.data.searcheRecordDiy[index]
    let latitude = Number(parkData.latitude)
    let longitude = Number(parkData.longitude)
    wx.openLocation({
      latitude,
      longitude,
      name: parkData.parkName,
      address: parkData.parkAddress,
      scale: 14
    })
  },
  /**
   * 在地图中打开搜索位置
   */
  searchToMap(e) {
    let index = e.currentTarget.dataset.index;
    let parkData = this.data.searchResultDiy[index]
    let latitude = Number(parkData.location.lat)
    let longitude = Number(parkData.location.lng)
    wx.openLocation({
      latitude,
      longitude,
      name: parkData.title,
      address: parkData.address,
      scale: 14
    })
  },
  /**
   * 在地图中打开适用车场位置
   */
  applyParkToMap(e) {
    let index = e.currentTarget.dataset.index;
    let parkData = this.data.applyPark[index]
    let latitude = Number(parkData.latitude)
    let longitude = Number(parkData.longitude)
    wx.openLocation({
      latitude,
      longitude,
      name: parkData.parkName,
      address: parkData.parkAddress,
      scale: 14
    })
  },
  /**
   * 设置月卡用户协议
   */
  setAgreementVip() {
    this.setData({
      agreementVip: !this.data.agreementVip
    })
  },
  /**
   * 设置定制月卡用户协议
   */
  // setAgreementDiy() {
  //   this.setData({
  //     agreementDiy: !this.data.agreementDiy
  //   })
  // },
  /**
   * 查询支付状态
   */
  getPayState(cardType, orderCode) {
    let url = '/customer/card/validatePayState'
    let parmas = {
      cardType: cardType,
      orderCode: orderCode
    }
    request.http(url, 'POST', parmas)
      .then(res => {
        log.info('接口' + url + ':' + JSON.stringify(res.data))
        if (res.data.code) {
          Toast.success('开通成功，下次停车即可享用服务');
          wx.redirectTo({
            url: '../grade/grade'
          })
        } else {
          wx.showToast({
            title: '开通失败，稍后重试',
            icon: 'none'
          })
        }
      })
  },
  /**
   * 显示优惠券弹窗
   */
  showCouponDialog() {
    if (this.data.couponList.length <= 0) {
      wx.showToast({
        title: '暂无优惠券可用',
        icon: 'none'
      })
      return
    }
    this.setData({
      couponDialog: true
    })
  },
  /**
   * 隐藏优惠券弹窗
   */
  hideCouponDialog() {
    this.setData({
      couponDialog: false
    })
  },
  /**
   * 查询优惠券
   */
  getCoupon() {
    let that = this
    let url = '/ticket/getNotExpiredValidTicket'
    let parmas = {
      cardType: 'MONTH',
      amount: 500
    }
    request.http(url, 'POST', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          let coupon = data.data
          for (var i = 0; i < coupon.length; i++) {
            coupon[i].checked = false
          }
          that.setData({
            couponList: coupon
          })
        }
      })
  },
  getDiscount(e) {
    let index = e.currentTarget.dataset.index
    let couponIndex = this.data.couponIndex
    let coupon = this.data.couponList
    console.log(index == couponIndex);
    if (index == couponIndex) {
      coupon[index].checked = false
      this.setData({
        checkedCouopn: {},
        couponIndex: -1
      })
    } else {
      for (var i = 0; i < coupon.length; i++) {
        if (index == i) {
          coupon[i].checked = true
        } else {
          coupon[i].checked = false
        }
      }
      this.setData({
        checkedCouopn: coupon[index],
        couponIndex: index
      })
    }
    this.setData({
      couponList: coupon
    })
    this.hideCouponDialog()
  },
  /**
   * 计算优惠价格
   */
  countCoupon(parmas, callback) {
    let url = '/customer/card/getDiscountAmontWithTicket'
    // let parmas = {
    //   paidAmount: 1,
    //   receivableAmount: 1,
    //   ticketId: 1,
    //   customerId: wx.getStorageSync('customerId')
    // }
    parmas['customerId'] = wx.getStorageSync('customerId')
    request.http(url, 'POST', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          callback(data)
        }
      })
      .catch(err => {
        timeFlag = false
        diyMonthFlag = false
        monthFlag = false
      })
  },
  /**
   * 计算两点之间距离
   * @param {Object} from 起始位置经纬度
   * @param {Array} to 终点位置经纬度
   * @param {Function} callback 回调函数
   */
  calculateDistance(from, to, callback) {
    qqmapsdk.calculateDistance({
      mode: 'driving',
      from,
      to,
      success(res) {
        callback(res)
      },
      fail: function (error) {
        console.error(error);
      },
    })
  },
  /**
   * 跳转支付页
   */
  toPayment() {
    // wx.navigateTo({
    //   url: '/pages/webView/payWebView/payWebView?src=https://mobile-test.lmtc.zmzncs.com/file/pay/index.html',
    // })
    if (!this.data.agreementVip) {
      Toast('请先阅读并同意会员服务协议')
      return
    }
    // 这是未绑定车牌弹出绑定车牌的  去掉这个
    // if (this.data.carNumList != null && this.data.carNumList.length > 0) { 
    // } else {
    //   this.showforbidShow();
    //   return 
    // }
    // this.setData({ btnLoading: true })   //支付按钮加载样式
    // 定制月卡
    let diyCardIndex = this.data.diyCardIndex
    let diyParkList = this.data.checkParkList;
    let diyCardList = this.data.diyCardList;
    let checkParkList = this.data.checkParkList;
    // 普通月卡
    let cardIndex = this.data.cardIndex
    let monthPayRule = this.data.monthPayRule;
    // 时长卡
    let timeIndex = this.data.timeIndex
    let timerPayRule = this.data.timerPayRule;

    let parkIds = []
    let data = {}
    // let type = this.data.tabbarIndex == 0 ? cardIndex != -1 ? 'MONTH' : 'DURATION' : 'CUSTOMIZE'
    let type = this.data.tabbarIndex == 0 ? 'skype' : this.data.tabbarIndex == 1 && cardIndex != -1 ? 'MONTH' : 'CUSTOMIZE'
    if (this.data.tabbarIndex == 2) {
      if (diyParkList.length <= 0) {
        wx.showToast({ title: '请先添加停车场', icon: 'none' })
        return
      }
    }
    if (type == 'MONTH') {
      console.log('月租卡信息', monthPayRule)
      if (!monthPayRule[cardIndex]) {
        wx.showToast({ title: '请选择月卡规则', icon: 'none' })
        return
      }
      data = {
        paidAmount: monthPayRule[cardIndex].sumAmount,
        monthRuleId: monthPayRule[cardIndex].monthRuleId,
        monthRentTypeId: monthPayRule[cardIndex].monthRentTypeId,
        uniformRentType: monthPayRule[cardIndex].uniformRentType,
        parkList: this.data.nowParkList,
        type: type
      }
    } else if (type == 'DURATION') {
      if (!timerPayRule[timeIndex]) {
        wx.showToast({ title: '请选择时长规则', icon: 'none' })
        return
      }
      data = {
        paidAmount: timerPayRule[timeIndex].amount,
        durationRuleId: timerPayRule[timeIndex].durationRuleId,
        durationRuleFeeScaleId: timerPayRule[timeIndex].id,
        duration: timerPayRule[timeIndex].duration,
        parkList: this.data.nowParkList,
        total: this.data.applyPark.length,
        type: type
      }

    } else if (type == 'CUSTOMIZE') {
      if (!diyCardList[diyCardIndex]) {
        wx.showToast({ title: '请选择定制月卡规则', icon: 'none' })
        return
      }
      if (!diyCardList[diyCardIndex].sumAmount) {
        if (diyCardIndex == 0) {
          diyCardIndex = 1
        }
      }
      data = {
        paidAmount: diyCardList[diyCardIndex].sumAmount,
        monthRentTypeId: diyCardIndex == 0 ? '1' : diyCardIndex == 1 ? '2' : '3',
        parkList: checkParkList,
        type: type
      }
      if (diyParkList.length == 1) {
        data['type'] = 'MONTH'
        data['monthRuleId'] = diyCardList[diyCardIndex].monthRuleId
        data['parkList'] = checkParkList[0]
      }
    } else if (type == 'skype') {
      if (this.data.skypeMoney <= 0) {
        wx.showToast({ title: '请输入您要充值的金额', icon: 'none' })
        return
      }
      if (this.data.skypeMoney > 9999) {
        wx.showToast({ title: '请输入9999以下数字', icon: 'none' })
        return
      }
      data = {
        paidAmount: this.data.skypeMoney,
        type: type
      }
    }
    console.log('会员卡信息：', data)
    wx.navigateTo({
      url: '/pages/confirmOrder/confirmOrder?payData=' + JSON.stringify(data),
    })
  }
})